//
//  XFAccount.m
//  SinaBlog_OC
//
//  Created by macs on 15/11/11.
//  Copyright © 2015年 BlackTail. All rights reserved.
//

#import "XFAccount.h"

@implementation XFAccount

//对象方法存档操作
- (void)saveAccount {

  NSString *path = [[NSSearchPathForDirectoriesInDomains(
      NSDocumentDirectory, NSUserDomainMask, YES) lastObject]
      stringByAppendingPathComponent:@"account.plist"];
  [NSKeyedArchiver archiveRootObject:self toFile:path];
}

+ (XFAccount *)getAccount {
  NSString *path = [[NSSearchPathForDirectoriesInDomains(
      NSDocumentDirectory, NSUserDomainMask, YES) lastObject]
      stringByAppendingPathComponent:@"account.plist"];
//    NSLog(@"%@",path);
  XFAccount *account = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
  //判断用户 token 值是否过期
  if ([account.expires_date compare:[NSDate date]] == NSOrderedDescending) {
    return account;
  }
  return nil;
}

- (void)setExpires_in:(NSTimeInterval)expires_in {

  _expires_in = expires_in;

  self.expires_date = [NSDate dateWithTimeIntervalSinceNow:expires_in];
}

//解档
- (instancetype)initWithCoder:(NSCoder *)coder {
  self = [super init];
  if (self) {
    _uid = [coder decodeObjectForKey:@"uid"];
    _name = [coder decodeObjectForKey:@"name"];
    _expires_in = [coder decodeDoubleForKey:@"expires_in"];
    _access_token = [coder decodeObjectForKey:@"access_token"];
    _avatar_large = [coder decodeObjectForKey:@"avatar_large"];
    _expires_date = [coder decodeObjectForKey:@"expires_date"];
  }
  return self;
}
//归档
- (void)encodeWithCoder:(NSCoder *)aCoder {
  [aCoder encodeObject:_avatar_large forKey:@"avatar_large"];
  [aCoder encodeObject:_access_token forKey:@"access_token"];
  [aCoder encodeDouble:_expires_in forKey:@"expires_in"];
  [aCoder encodeObject:_name forKey:@"name"];
  [aCoder encodeObject:_uid forKey:@"uid"];
  [aCoder encodeObject:_expires_date forKey:@"expires_date"];
}

- (NSString *)description {

  NSArray *keys = @[
    @"access_token",
    @"avatar_large",
    @"expires_in",
    @"name",
    @"uid",
    @"expires_date"
  ];
  return [[self dictionaryWithValuesForKeys:keys] description];
}

+ (instancetype)accountWithDict:(NSDictionary *)dict {

  XFAccount *account = [[XFAccount alloc] init];

  [account setValuesForKeysWithDictionary:dict];
  return account;
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {
}

@end
